package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * ClassName: MyJwtUtils
 * Description:
 *
 * @Author hy
 * @Create 29/8/2024 下午4:43
 * @Version 1.0
 */
public class MyJwtUtils {
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());
    public static String createToken(Long id, String username){
        String jwt = Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis()+3600000))
                .setSubject("USER_LOGIN")
                .claim("userId",id)
                .claim("userName",username)
                .signWith(tokenSignKey)
                .compact();
        return jwt;
    }
    public static void parseToken(String token){

        if(token == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            jwtParser.parseClaimsJws(token);
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
    public static void main(String[] args) {
        String token = MyJwtUtils.createToken(2L,"user");
        System.out.println(token);
        MyJwtUtils.parseToken(token);
    }
}